package com.itheima.mqtt.client;

import com.itheima.mqtt.enums.QosEnum;
import com.itheima.mqtt.properties.MqttProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

//@Component
public class RunEmq {

    @Autowired
    private EmqClient emqClient;

    @Autowired
    private MqttProperties properties;

    @PostConstruct
    public void init() {
        //连接服务器
        System.out.println("--------------------------------");
        properties.toString();
        System.out.println("--------------------------------");

        emqClient.connect(properties.getUsername(), properties.getPassword());
        //订阅一个主题
        emqClient.subscribe("testtopic/#", QosEnum.QoS2);
        //开启一个新的线程 每隔5秒去向 testtopic/123
        new Thread(() -> {
            while (true) {
                emqClient.publish("testtopic/123",
                        "publish msg :" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME),
                        QosEnum.QoS2, false);
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
